<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>

    <template v-slot:table>
      <div class="w100p table" ref="table">
        <div class="drugsList" ref="drugsList">
          <div class="drugInfo" v-for="item, index in facilityOutPutList" :key="index">
            <div class="point"></div>
            <div>养殖设施：<span class="info">{{ item.facilityName }}</span></div>
            <div>药品名称：<span class="info">{{ item.materialName }}</span></div>
            <div>总用量：<span class="info">{{ item.amount || '-' }}</span>{{ materialUnit[item.materialNo] }}</div>
            <div>亩均用量：<span class="info">{{ item.averageNum || '-' }}</span>{{ materialUnit[item.materialNo] }}</div>
          </div>
        </div>
        <div class="echarts" ref="echarts" v-show="facilityOutPutList.length > 0">
          <!-- <LineCharts></LineCharts> -->
          <HorizontalBarChart v-if="retsetEcharts" :options="chartOptions"></HorizontalBarChart>
        </div>
      </div>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import SearchForm from '@/components/SearchForm';
import BarEchart from './components/barEchart.vue';
import HorizontalBarChart from "./components/horizontalBarChart.vue";
import diseaseFollowUp from '@/api/healthManagement/diseaseFollowUp.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import { formatTime } from '@/utils/fmtTime.js';
export default {
  components: { MainSlot, SearchForm, BarEchart, HorizontalBarChart },
  data() {
    return {
      retsetEcharts: false,
      unfoldFlag: false,
      loading: false,
      isShowEcharts: false,
      formData: {},
      height: '',
      materialList: [],
      facilityOutPutList: [],
      materialObj: {},
      materialUnit: {},
      facilityList: [],
      searchFormData: {
        isYear: '1'
      },
      chartOptions: {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            // console.log(params,this)
            let text = [params[0].name + `(${this.materialObj[this.searchFormData.materialNo]})`];
            let desc = this.materialUnit[this.searchFormData.materialNo];
            if (params[0]) {
              var data = params[0].data || '--';
              var seriesName = params[0].seriesName || '--';
              text.push(seriesName + ': ' + data + desc)
            }
            if (params[1]) {
              var data_1 = params[1].data || '--';
              var seriesName_1 = params[1].seriesName || '--';
              text.push(seriesName_1 + ': ' + data_1 + desc)
            }
            return text.join('</br>');
          }
        },
        grid: {
          top: 100,
          left: 120,
          right: 50
        },
        legend: {
          data: ['亩均用量', '总用量']
        },
        xAxis: {
          type: 'value',
          name: ''
        },
        yAxis: {
          dfsafsafas: 'dfafsad',
          type: 'category',
          data: []
        },
        series: [{
          data: [],
          type: 'bar',
          name: '亩均用量'
        },
        {
          data: [],
          type: 'bar',
          name: '总用量'
        }]
      },
      isYear: false,
      formItemList: [
        {
          label: '药品名称',
          type: 'select',
          selectOptions: [],
          param: 'materialNo',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }, {
          label: '养殖设施',
          type: 'select',
          selectOptions: [],
          param: 'facilityIdList',
          defaultSelect: '',
          multiple: true,
          collapseTags: true,
          isShow: true
        }, {
          label: '按年/日期查',
          type: 'select',
          selectOptions: [{ value: 'isYear', text: '按年查' }, { value: 'noYear', text: '按月查' }],
          param: 'isYear',
          defaultSelect: 'noYear',
          isShow: true
        }, {
          label: '养殖日期',
          type: 'datetimerange',
          param: 'dataList',
          isShow: true
        }, {
          label: '年份',
          type: 'year',
          param: 'queryYear',
          isShow: true
        },
      ]
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      let { data: materialList } = await materialApi.getqueryList({});
      this.materialList = materialList;
      this.materialList = this.materialList.filter(data => {
        return data.materialTypeNo == '4165464165465146516' || data.materialTypeNo == '1077222993386450944'
      })
      this.materialObj = {};
      this.materialList.forEach(item => {
        this.materialObj[item.materialNo] = item.materialName;
        this.materialUnit[item.materialNo] = item.unitName || item.perSpecUnitName;
      })
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.facilityIdList = this.facilityList.map(item => { return item.facilityId });

      this.searchFormData.materialNo = this.materialList[0] ? this.materialList[0].materialNo : '';
      this.queryByFacility();
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityIdList') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('materialNo') !== -1) {
          console.log(this.materialList)
          let selectOptions = this.materialList.map(data => {
            return {
              text: data.materialName, value: data.materialNo
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    search(data) {
      console.log(data.queryYear)
      if (!data.isYear && data.dataTimeList && data.queryYear) {
        this.$message.warning('请选择按年/按日期查询')
        return
      } else {
        if (data.isYear == 'noYear'||!data.isYear) {
          this.isYear = false;
        } else {
          this.isYear = true;
        }
      }
      let dataList = data.dataList && data.dataList.length ? data.dataList || [] : []
      this.searchFormData = {
        materialNo: data.materialNo,
        materialName: this.materialObj[data.materialNo] || '',
        facilityIdList: data.facilityIdList || [],
        startDate: dataList[0] || null,
        endDate: dataList[1] || null,
        queryYear: data.queryYear ? new Date(data.queryYear).getFullYear() : null
      }
      this.queryByFacility()
    },
    queryByFacility() {
      let params = [];
      //获取单位不是亩或者平方米的设施
      let noqueryList = this.facilityList.filter(item => {
        return !item.unitName || !(item.unitName == '亩' || item.unitName == '平方米') || !item.scope
      })
      //获取单位是亩或者平方米的设施
      let queryList = this.facilityList.filter(item => {
        console.log(item.facilityName, item.unitName && item.scope && (item.unitName == '亩' || item.unitName == '平方米'))
        return item.unitName && item.scope && (item.unitName == '亩' || item.unitName == '平方米')
      })
      //单位不是亩或者平方米的设施做出提示
      if (noqueryList.length > 0) {
        let textList = queryList.map(item => {
          return item.facilityName
        })
        this.$message.warning(textList.join(';') + ';未配置面积或单位配置非面积单位，请重新配置单位为亩或者平方米!')
      }
      //重置表格数据

      this.$set(this.chartOptions.yAxis, 'data', []);
      this.$set(this.chartOptions, 'series', [{
        data: [],
        type: 'bar',
        name: '总用量',
        barWidth: 20
      }, {
        data: [],
        type: 'bar',
        name: '亩均用量',
        barWidth: 20
      }]);
      //符合条件的设施获取设施的基本数据请求产量分析
      queryList.forEach(item => {
        let newDate = new Date();
        let year = new Date().getFullYear();
        let materialNo = this.searchFormData.materialNo;
        let materialName = this.searchFormData.materialName;
        let startDate = '';
        let endDate = '';
        let facilityIdList = this.searchFormData.facilityIdList || [];
        let unitName = item.unitName;
        let scope = item.scope;
        if (this.isYear) {
          let y = this.searchFormData.queryYear || year
          startDate = `${y}-01-01`;
          endDate = `${y}-12-31`;
        } else if (!this.isYear) {
          startDate = this.searchFormData.startDate || formatTime(newDate.setDate(newDate.getDate() - 15), 'yyyy-MM-dd');
          endDate = this.searchFormData.endDate || formatTime(newDate.setDate(newDate.getDate() + 16), 'yyyy-MM-dd');
        }
        this.chartOptions.yAxis.data.push(item.facilityName);
        this.chartOptions.series[0].data.push(0);
        if (facilityIdList.length == 0 || (facilityIdList.length > 0 && facilityIdList.includes(item.facilityId))) {
          if (materialNo) {
            params.push({
              facilityId: item.facilityId,
              facilityName: item.facilityName,
              scope: scope,
              unitName: unitName,
              materialNo: materialNo,
              materialName: materialName,
              startDate: startDate,
              endDate: endDate,
            })
          }
        }
      })
      //重置图标
      this.retsetEcharts = false;
      this.facilityOutPutList = [];
      if (params.length == 0) return;
      diseaseFollowUp.queryByFacility(params).then(res => {
        this.retsetEcharts = true;
        if (res.code) {
          this.chartOptions.yAxis.data = []
          this.chartOptions.series[0].data = [];
          this.chartOptions.series[1].data = [];
          if (res.data.length) {
            this.facilityOutPutList = res.data;
            res.data.forEach((item, index) => {
              item.facilityName = item.facilityName || queryList[index].facilityName
              this.chartOptions.yAxis.data.push(item.facilityName);
              this.chartOptions.series[0].data.push(item.amount || 0);
              this.chartOptions.series[1].data.push(item.averageNum || 0);
            })
          } else {
            this.facilityOutPutList = []
          }
        } else {
          this.$message.warning(res.msg || '查询产量失败')
        }
      }).catch(err => {
        console.log(err);
        this.$message.warning(err)
      })
    },
    getEchartHeight() {
      this.isShowEcharts = false;
      setTimeout(() => {
        let drugsList_H = this.$refs.drugsList?.clientHeight;
        let table_H = this.$refs.table?.clientHeight;
        console.log(table_H - drugsList_H)
        this.$refs.echarts.style.height = `${table_H - drugsList_H}px`;
        this.height = `${table_H - drugsList_H - 40}px`;
        this.isShowEcharts = true;
      }, 1000);
    },
  }
};
</script>

<style lang="scss" scoped>
.table {
  height: 100%;
}

.drugsList {
  width: 100%;
  max-height: 200px;
  min-height: 100px;
  padding: 0 20px;
  overflow-y: auto;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  transition: all 0.2s;

  .drugInfo {
    width: 50%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 14px;
    line-height: 36px;

    .point {
      width: 10px;
      height: 10px;
      background: #02a0fc;
    }

    &>div {
      margin-right: 20px;

      .info {
        color: #999999;
      }
    }
  }

}

.drugsList:hover {
  background: #f1f1f1;
}

.echarts {
  padding: 20px;
}

.facilityOutPutList {
  display: block;
  width: 100%;
  text-align: center;
  color: #02a0fc;
}
</style>